package com.cucn.ingmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cucn.common.constant.product.ProductConstant;
import com.cucn.common.utils.PageUtils;
import com.cucn.common.utils.Query;
import com.cucn.ingmall.product.dao.AttrAttrgroupRelationDao;
import com.cucn.ingmall.product.dao.AttrDao;
import com.cucn.ingmall.product.dao.AttrGroupDao;
import com.cucn.ingmall.product.dao.CategoryDao;
import com.cucn.ingmall.product.entity.AttrAttrgroupRelationEntity;
import com.cucn.ingmall.product.entity.AttrEntity;
import com.cucn.ingmall.product.entity.AttrGroupEntity;
import com.cucn.ingmall.product.entity.CategoryEntity;
import com.cucn.ingmall.product.service.AttrService;
import com.cucn.ingmall.product.service.CategoryService;
import com.cucn.ingmall.product.vo.AttrGroupRelationVO;
import com.cucn.ingmall.product.vo.AttrResponseVO;
import com.cucn.ingmall.product.vo.AttrVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品属性
 *
 * @author kouchaojie
 * @email kou1688@foxmail.com
 * @date 2021-11-17 16:27:03
 */
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 新增商品属性
     * 首先保存属性的基本信息,然后保存关联表的信息
     *
     * @param attr 商品属性VO类
     */
    @Override
    @Transactional
    public void saveAttr(AttrVO attr) {
        //保存基本数据
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);

        //保存关联关系
        //如果是基本属性才保存关联
        if (ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() == (attr.getAttrType()) && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relation = new AttrAttrgroupRelationEntity();
            relation.setAttrId(attrEntity.getAttrId());
            relation.setAttrGroupId(attr.getAttrGroupId());

            relationDao.insert(relation);
        }
    }

    /**
     * 通过分类id查询规格参数列表
     * 需要区分刚进入页面不带id查询全部与点击分类带id查询特定的分类
     *
     * @param params    请求参数
     * @param catelogId 分类id
     * @param type      商品属性类型
     * @return 分页数据
     */
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        //得到条件查询的数据
        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type",
                        //判断基本属性还是销售属性
                        ProductConstant.AttrEnum.ATTR_TYPE_BASE.getMsg()
                                .equalsIgnoreCase(type) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        //select ** from ** where catelog_id=catelogId and attr_id=key or attr_name=key
        //是否带分类查询
        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }

        //如果有条件查询
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((obj) -> {
                obj.like("attr_name", key).or().eq("attr_id", key);
            });
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        //封装为分页数据
        PageUtils pageUtils = new PageUtils(page);

        //获取分页记录列表
        List<AttrEntity> records = page.getRecords();
        List<AttrResponseVO> responseVOS = records.stream()
                .map((attrEntity) -> {
                            AttrResponseVO attrResponseVO = new AttrResponseVO();
                            BeanUtils.copyProperties(attrEntity, attrResponseVO);

                            //获取属性分组名与分类名
                            //如果是基本属性才设置属性分组
                            if (ProductConstant.AttrEnum.ATTR_TYPE_BASE.getMsg().equalsIgnoreCase(type)) {
                                AttrAttrgroupRelationEntity attrAttrgroupRelation =
                                        relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                                                .eq("attr_id", attrResponseVO.getAttrId()));
                                //属性分组有可能为空,不为空时才去查询关联关系
                                if (attrAttrgroupRelation != null && attrAttrgroupRelation.getAttrGroupId() != null) {
                                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelation.getAttrGroupId());
                                    attrResponseVO.setGroupName(attrGroupEntity.getAttrGroupName());
                                }
                            }

                            CategoryEntity categoryEntity = categoryDao.selectById(attrResponseVO.getCatelogId());
                            if (categoryEntity != null) {
                                attrResponseVO.setCatelogName(categoryEntity.getName());
                            }

                            return attrResponseVO;
                        }
                ).collect(Collectors.toList());

        //结果集需要返回最新的结果集
        pageUtils.setList(responseVOS);

        return pageUtils;
    }

    /**
     * 查询属性详情
     *
     * @param attrId 属性id
     * @return 统一结果返回-商品属性（规格参数）响应VO类（带三级分类路径）
     */
    @Override
    @Cacheable(value = "attr", key = "'attrInfo:'+#root.args[0]")
    public AttrResponseVO getAttrInfo(Long attrId) {
        AttrResponseVO responseVO = new AttrResponseVO();
        //查出基础信息
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, responseVO);

        if (ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() == responseVO.getAttrType()) {
            //设置属性分组的信息(分组id与分组名)
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>()
                            .eq("attr_id", attrId));
            if (relationEntity != null) {
                Long attrGroupId = relationEntity.getAttrGroupId();
                responseVO.setAttrGroupId(attrGroupId);
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                if (attrGroupEntity != null) {
                    responseVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        //设置分类信息(分类id与完整分类路径)
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        responseVO.setCatelogPath(catelogPath);

        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null) {
            responseVO.setCatelogName(categoryEntity.getName());
        }

        return responseVO;
    }

    /**
     * 修改商品属性(规格参数)
     *
     * @param attr 修改的商品属性信息
     */
    @Override
    @Transactional
    public void updateAttr(AttrVO attr) {
        //修改基本信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);

        if (ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() == attrEntity.getAttrType()) {
            //修改属性与属性分组关联表信息(属性id与属性分组id)
            AttrAttrgroupRelationEntity attrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrgroupRelationEntity.setAttrId(attr.getAttrId());
            attrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());

            //如果关联表中没有属性记录,则新增
            Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attr.getAttrId()));
            if (count > 0) {
                relationDao.update(attrgroupRelationEntity,
                        new UpdateWrapper<AttrAttrgroupRelationEntity>()
                                .eq("attr_id", attr.getAttrId()));
            } else {
                relationDao.insert(attrgroupRelationEntity);
            }
        }

    }

    /**
     * 根据分组id查找关联的所有基本属性（规格参数）
     *
     * @param attrgroupId 属性分组id
     * @return attrgroupId对应的所有关联的属性的信息
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        //查出属性分组对应关联信息
        List<AttrAttrgroupRelationEntity> entities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        //用关联信息查出所有属性信息
        List<Long> attrIds = entities.stream().map((attr) -> {
            //查出所有属性id
            return attr.getAttrId();
        }).collect(Collectors.toList());

        if (!attrIds.isEmpty()) {
            //通过属性id查出所有属性信息
            List<AttrEntity> attrList = this.listByIds(attrIds);
            return attrList;
        } else {
            return null;
        }
    }

    /**
     * 删除属性与分组的关联关系
     *
     * @param vos 需删除的关联关系[{"attrId":1,"attrGroupId":2}]
     */
    @Override
    public void deleteRelation(List<AttrGroupRelationVO> vos) {
        //将请求体的vos转换为关联关系对象进行批量删除
        List<AttrAttrgroupRelationEntity> relationEntities = vos.stream().map((attr) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(attr, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());

        relationDao.deleteBatchRelation(relationEntities);
    }

    /**
     * 查询所有可被检索的属性id
     *
     * @param attrIdList 属性id集合
     * @return 可被检索的属性id
     */
    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIdList) {

        return baseMapper.selectSearchAttrIds(attrIdList);
    }
}